﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/07/04
 * 
 * 功能说明：内容搜索控件
 * 
 * 修改人员：yylu
 * 
 * 修改日期：2009/06/09
 * 
 * 修改记录：1)修改搜索结果翻页问题，把搜索结果从viewstate保存改为直接读取url地址 2009/06/09 yylu
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Whir.Common.WebHelper;

public partial class UserControls_ContentControl_ContentSearch : System.Web.UI.UserControl, ISearchUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //初始化控件
        InitSearchText();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string urlwhere = geturlWhere().ToLower();

        string[] url = NetRequest.GetUrl().Split('?');

        string[] urlpara = url[1].Split('&');


        string strUrl = url[0].ToString() + "?";
        for (int k = 0; k < urlpara.Length; k++)
        {
            string[] paraName = urlpara[k].Split('=');
            if (urlwhere.IndexOf(paraName[0].ToString().ToLower()) > 0)
            {
                //strUrl += paraName[0] + "=" + 
            }
            else
            {
                strUrl += paraName[0].ToString() + "=" + paraName[1].ToString() + "&";
            }
        }
        if (urlwhere != "")
        {
            urlwhere = urlwhere.Substring(1);
        }

        Response.Redirect(strUrl + urlwhere, true);
    }

    #region 初始化搜索控件
    /// <summary>
    /// 初始化搜索控件
    /// </summary>
    private void InitSearchText()
    {
        Whir.BLL.Whir_ModelForm modelFormbll = new Whir.BLL.Whir_ModelForm();
        Whir.Model.Whir_ModelForm modelFormModel = new Whir.Model.Whir_ModelForm();
        modelFormModel = modelFormbll.GetModel(ModelFormID);
        string searchFields = modelFormModel.formsearch;

        if (!string.IsNullOrEmpty(searchFields))
        {
            InitSearchControls(searchFields);
        }

        //if (modelFormModel.timespanSearch)
        //{
        //    InitTimeSpanSearch();
        //}
    }

    #endregion

    /// <summary>
    /// 初始化一般搜索
    /// </summary>
    /// <param name="searchFields">字段列表</param>
    protected void InitSearchControls(string searchFields)
    {
        string fieldId = "", fieldIds = "";
        string fieldName = "", fieldNames = "";
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();

        Literal lit;
        DropDownList list;
        string strRequest = "";

        lit = new Literal();
        lit.ID = "table1";
        lit.Text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\" id=\"Table1\"><tr>";
        divSearchContents.Controls.Add(lit);

        int dateNum = 0;
        for (int i = 0; i < searchFields.Split(',').Length; i++)
        {
            fieldId = searchFields.Split(',')[i].ToString();
            fieldModel = fieldBll.GetModel(int.Parse(fieldId));
            fieldName = fieldModel.fieldName;

            fieldIds += fieldId + ",";
            fieldNames += fieldName + ",";

            if (searchFields.Split(',').Length >= 3 && (i + dateNum) % 3 == 0 && i != 0)
            {
                lit = new Literal();
                lit.ID = "tr1"+i.ToString();
                lit.Text = "</tr><tr>";
                divSearchContents.Controls.Add(lit);
            }

            if ((FieldType)fieldModel.fieldType == FieldType.DateTimeType)
            {
                if ((i + dateNum + 1) % 3 == 0)
                {
                    lit = new Literal();
                    lit.ID = "tr1" + i.ToString();
                    lit.Text = "<td width=\"66%\"></td></tr><tr>";
                    divSearchContents.Controls.Add(lit);
                }
                dateNum++;
                lit = new Literal();
                lit.ID = fieldModel.fieldID.ToString() + "b";
                lit.Text = "<td colspan=\"2\" width=\"66%\">";
                divSearchContents.Controls.Add(lit);
            }
            else
            {
                lit = new Literal();
                lit.ID = fieldModel.fieldID.ToString() + "b";
                lit.Text = "<td width=\"33%\">";
                divSearchContents.Controls.Add(lit);
            }

            //查询条件
            divSearch.Visible = true;
            Label lbTitle = new Label();
            lbTitle.ID = "lbTitle" + i;
            lbTitle.Font.Bold = true;
            lbTitle.Text = "&nbsp;&nbsp;" + fieldModel.alias + "：";            
            divSearchContents.Controls.Add(lbTitle);
            
            switch ((FieldType)fieldModel.fieldType)
            {
                case FieldType.BoolType:
                    list = new DropDownList();
                    list.ID = "list_" + fieldModel.fieldName;
                    list.Items.Insert(0, new ListItem("否", "否"));
                    list.Items.Insert(0, new ListItem("是", "是"));
                    list.Items.Insert(0, new ListItem("--请选择--", "-1"));

                    //if (getViewState("list_" + fieldModel.fieldName) != "")
                    //{
                    //    list.SelectedValue = getViewState("list_" + fieldModel.fieldName);
                    //}

                    if (Request.QueryString[fieldModel.fieldName] != null)
                    {
                        strRequest = NetRequest.SafeRequest(Page, fieldModel.fieldName);
                        if (strRequest != "")
                        {
                            list.SelectedValue = strRequest;
                        }
                    }

                    divSearchContents.Controls.Add(list);
                    lit = new Literal();
                    lit.ID = fieldModel.fieldID.ToString() + "e";
                    lit.Text = "</td>";
                    divSearchContents.Controls.Add(list);
                    break;
                case FieldType.ColorType:
                case FieldType.FileType:
                case FieldType.LinkType:
                case FieldType.ListBoxType:
                    list = new DropDownList();
                    list.ID = "list_" + fieldModel.fieldName;
                    list.Width = Unit.Parse("130");

                    Whir.BLL.Whir_FieldOption OptionBll = new Whir.BLL.Whir_FieldOption();
                    int fieldTextId = int.Parse(OptionBll.GetList(" FieldID = " + fieldModel.fieldID).Tables[0].Rows[0][0].ToString());
                    Whir.Model.Whir_FieldOption optionModel = OptionBll.GetModel(fieldTextId);

                    if (optionModel.bindType == 2)
                    {
                        list.DataSource = Whir.SQLServerDAL.DbHelperSQL.Query(optionModel.sql);
                        list.DataTextField = optionModel.textField;
                        list.DataValueField = optionModel.valueField;
                        list.DataBind();                        
                        list.Items.Insert(0, new ListItem("--请选择--", "-1"));
                    }
                    else if (optionModel.bindType == 3 || optionModel.bindType == 4)
                    {
                        list.DataSource = Whir.SQLServerDAL.DbHelperSQL.Query("SELECT " + optionModel.textField + "," + optionModel.valueField + " FROM " + optionModel.sql + " WHERE ParentID=" + optionModel.sqlChild);
                        list.DataTextField = optionModel.textField;
                        list.DataValueField = optionModel.valueField;
                        Whir.Common.BindHelper.BindDropDownList(list, optionModel.sql, optionModel.sqlChild, "", "");
                        list.Items.Insert(0, new ListItem("--请选择--", "-1"));
                    }
                    else if (optionModel.bindType == 5)
                    {
                        string strWhere = optionModel.sqlChild; //获得当前条修的
                        string[] strTemps = strWhere.Replace("\r\n", "|").Split('|');
                        int TypeID = NetRequest.GetQueryInt("TypeID"); //获取当前栏目编号
                        string sqlChild = "";  //当前栏目对应的类别父类

                        //获取当前类别所对应的规则类别
                        for (int j = 0; j < strTemps.Length; j++)
                        {
                            if (strTemps[j].Trim() != string.Empty)
                            {
                                string strTypeID = strTemps[j].Split('=')[0];
                                if (strTypeID != string.Empty && strTypeID == TypeID.ToString())
                                {
                                    sqlChild = strTemps[j].Split('=')[1];
                                    break;
                                }
                            }
                        }

                        if (sqlChild != string.Empty)
                        {
                            list.DataSource = Whir.SQLServerDAL.DbHelperSQL.Query("SELECT " + optionModel.textField + "," + optionModel.valueField + " FROM " + optionModel.sql + " WHERE ParentID=" + sqlChild);
                            list.DataTextField = optionModel.textField;
                            list.DataValueField = optionModel.valueField;
                            Whir.Common.BindHelper.BindDropDownList(list, optionModel.sql, sqlChild, "", "");
                            list.Items.Insert(0, new ListItem("--请选择--", "-1"));
                        }
                    }

                    //if (getViewState("list_" + fieldModel.fieldName) != "")
                    //{
                    //    list.SelectedValue = getViewState("list_" + fieldModel.fieldName);
                    //}
                    if (Request.QueryString[fieldModel.fieldName] != null)
                    {
                        strRequest = NetRequest.SafeRequest(Page, fieldModel.fieldName);
                        if (strRequest != "")
                        {
                            list.SelectedValue = strRequest;
                        }
                    }

                    
                    divSearchContents.Controls.Add(list);
                    lit = new Literal();
                    lit.ID = fieldModel.fieldID.ToString()+"e";
                    lit.Text = "</td>";
                    divSearchContents.Controls.Add(lit);
                    break;
                case FieldType.MoneyType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.MultipleTextType:
                case FieldType.NumberType:
                case FieldType.PictureType:
                case FieldType.TextType:
                    {
                        //查询文本框
                        TextBox lbTxtBox = new TextBox();
                        lbTxtBox.CssClass = "input_text";
                        lbTxtBox.ID = "lbTxtBox" + i;
                        lbTxtBox.Width = Unit.Parse("130");

                        //if (getViewState("lbTxtBox" + i) != "")
                        //{
                        //    lbTxtBox.Text = getViewState("lbTxtBox" + i);
                        //}
                        if (Request.QueryString[fieldModel.fieldName] != null)
                        {
                            strRequest = NetRequest.SafeRequest(Page, fieldModel.fieldName);
                            if (strRequest != "")
                            {
                                lbTxtBox.Text = strRequest;
                            }
                        }

                        divSearchContents.Controls.Add(lbTxtBox);

                        lit = new Literal();
                        lit.ID = fieldModel.fieldID.ToString() + "e";
                        lit.Text = "</td>";
                        divSearchContents.Controls.Add(lit);
                    }
                    break;
                case FieldType.DateTimeType:
                    {
                        TextBox lbTxtBox = new TextBox();
                        lbTxtBox.CssClass = "input_text";
                        lbTxtBox.Attributes.Add("onClick", "WdatePicker({dateFmt:'yyyy-MM-dd'})");
                        lbTxtBox.ID = "lbTxtBoxBegin" + i;
                        lbTxtBox.Width = Unit.Parse("130");

                        //if (getViewState("lbTxtBoxBegin" + i) != "")
                        //{
                        //    lbTxtBox.Text = getViewState("lbTxtBoxBegin" + i);
                        //}
                        if (Request.QueryString[fieldModel.fieldName+"_begin"] != null)
                        {
                            //strRequest = NetRequest.SafeRequest(Page, fieldModel.fieldName + "_begin");
                            strRequest = Request.QueryString[fieldModel.fieldName + "_begin"].ToString();
                            if (strRequest != "" && strRequest.Length <= 10)
                            {
                                lbTxtBox.Text = strRequest;
                            }
                        }
                        divSearchContents.Controls.Add(lbTxtBox);

                        lit = new Literal();
                        lit.ID = fieldModel.fieldID.ToString() + "zhi";
                        lit.Text = " 至 ";
                        divSearchContents.Controls.Add(lit);

                        lbTxtBox = new TextBox();
                        lbTxtBox.CssClass = "input_text";
                        lbTxtBox.Attributes.Add("onClick", "WdatePicker({dateFmt:'yyyy-MM-dd'})");
                        lbTxtBox.ID = "lbTxtBoxEnd" + i;
                        lbTxtBox.Width = Unit.Parse("130");

                        //if (getViewState("lbTxtBoxEnd" + i) != "")
                        //{
                        //    lbTxtBox.Text = getViewState("lbTxtBoxEnd" + i);
                        //}
                        if (Request.QueryString[fieldModel.fieldName + "_end"] != null)
                        {
                            //strRequest = NetRequest.SafeRequest(Page, fieldModel.fieldName + "_end");
                            strRequest = Request.QueryString[fieldModel.fieldName + "_end"].ToString();
                            if (strRequest != "" && strRequest.Length <= 10)
                            {
                                lbTxtBox.Text = strRequest;
                            }
                        }
                        divSearchContents.Controls.Add(lbTxtBox);

                        lit = new Literal();
                        lit.ID = fieldModel.fieldID.ToString() + "e";
                        lit.Text = "</td>";
                        divSearchContents.Controls.Add(lit);
                    }
                    break;
                //case FieldType.None:
                //    {
                //        DropDownList list = new DropDownList();
                //        list.DataSource = Whir.SQLServerDAL.DbHelperSQL.GetDataTable("*", "Whir_Column", "parentID  = (select parentID from whir_column where ColumnID = " + TypeID + ")", "createDate");
                //        list.DataTextField = "columnName";
                //        list.DataValueField = "columnID";
                //        list.DataBind();
                //        list.ID = "list";
                //        divSearchContents.Controls.Add(list);
                //    }
                //    break;
            }
        }

        hdFieldIDs.Value = fieldIds.TrimEnd(',');
        hdFieldNames.Value = fieldNames.TrimEnd(',');

        lit = new Literal();
        lit.ID = "table2";
        lit.Text = "</tr></table>";
        divSearchContents.Controls.Add(lit);
    }

    private string strWhere = "";
    public string SQLWhere
    {
        set { strWhere = value; }
        get { return strWhere; }
    }


    /// <summary>
    /// 获取urlwhere 
    /// </summary>
    /// <returns></returns>
    private string geturlWhere()
    {
        IContentUserControl userControl1 = (IContentUserControl)Page.FindControl("CommonContentManage1");

        string fieldId = "", fieldName = "";
        string fieldIds = hdFieldIDs.Value;
        string fieldNames = hdFieldNames.Value;
        string Where = "";
        string urlwhere = "";

        //Where = "TypeID=" + TypeID;
        for (int i = 0; i < fieldNames.Split(',').Length; i++)
        {
            fieldId = fieldIds.Split(',')[i].ToString();
            fieldName = fieldNames.Split(',')[i].ToString();

            Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
            Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();
            fieldModel = fieldBll.GetModel(int.Parse(fieldId));

            switch ((FieldType)fieldModel.fieldType)
            {
                case FieldType.BoolType:
                    DropDownList listBool = divSearchContents.FindControl("list_" + fieldName) as DropDownList;
                    if (listBool != null)
                    {
                        if (!string.IsNullOrEmpty(listBool.SelectedValue.Trim()))
                        {
                            if (listBool.SelectedValue != "-1")
                            {
                                Where += " AND " + fieldName + " = '" + listBool.SelectedValue.Trim() + "'";

                                //setViewState("list_" + fieldName, listBool.SelectedValue.Trim());

                                urlwhere += "&" + fieldName + "=" + listBool.SelectedValue.Trim();
                            }
                            else
                            {
                                urlwhere += "&" + fieldName + "=";
                            }
                        }
                        else
                        {
                            urlwhere += "&" + fieldName + "=";
                        }
                    }
                    break;
                case FieldType.ColorType:
                case FieldType.FileType:
                case FieldType.LinkType:
                case FieldType.ListBoxType:
                    {
                        DropDownList tt = divSearchContents.FindControl("list_" + fieldName) as DropDownList;

                        if (tt != null)
                        {                            
                            Whir.BLL.Whir_FieldOption OptionBll = new Whir.BLL.Whir_FieldOption();
                            int fieldTextId = int.Parse(OptionBll.GetList(" FieldID = " + fieldModel.fieldID).Tables[0].Rows[0][0].ToString());
                            Whir.Model.Whir_FieldOption optionModel = OptionBll.GetModel(fieldTextId);


                            if (optionModel.bindType == 2)
                            {
                                if (tt.SelectedValue != "-1")
                                {
                                    Where += " AND " + fieldName + " = '" + tt.SelectedValue.Trim() + "' ";
                                }
                            }
                            else if (optionModel.bindType == 3 || optionModel.bindType == 4)
                            {
                                if (tt.SelectedValue != "-1")
                                {
                                    string typeIDs = tt.SelectedValue.Trim() + GetAllTypeID(tt.SelectedValue.Trim());
                                    Where += " AND " + fieldName + " IN (" + typeIDs + ") ";
                                }
                            }
                            else if (optionModel.bindType == 5)
                            {
                                if (tt.SelectedValue != "-1")
                                {
                                    string typeIDs = tt.SelectedValue.Trim();
                                    Where += " AND " + fieldName + " IN (" + typeIDs + ") ";
                                }
                            }

                            if (tt.SelectedValue != "-1")
                            {
                                //setViewState("list_" + fieldName, tt.SelectedValue.Trim());
                                urlwhere += "&" + fieldName + "=" + tt.SelectedValue.Trim();
                            }
                            else
                            {
                                urlwhere += "&" + fieldName + "=";
                            }
                        }

                    }
                    break;
                case FieldType.MoneyType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.MultipleTextType:
                case FieldType.NumberType:
                case FieldType.PictureType:
                case FieldType.TextType:
                    {
                        TextBox tt = divSearchContents.FindControl("lbTxtBox" + i) as TextBox;
                        if (tt != null)
                        {
                            if (!string.IsNullOrEmpty(tt.Text.Trim()))
                            {
                                Where += " AND " + fieldName + " like '%" + tt.Text.Trim() + "%'";

                                //setViewState("lbTxtBox" + i, tt.Text.Trim());

                                urlwhere += "&" + fieldName + "=" + tt.Text.Trim();
                            }
                            else
                            {
                                urlwhere += "&" + fieldName + "=";
                            }
                        }
                    }
                    break;
                case FieldType.DateTimeType:
                    {
                        //TextBox tt = divSearchContents.FindControl("lbTxtBox" + i) as TextBox;
                        //if (tt != null)
                        //{
                        //    if (!string.IsNullOrEmpty(tt.Text.Trim()))
                        //    {
                        //        Where += " AND datediff(day," + fieldName + ",'" + tt.Text.Trim() + "')=0";
                        //    }
                        //}


                        TextBox begintime = divSearchContents.FindControl("lbTxtBoxBegin" + i) as TextBox;
                        TextBox endtime = divSearchContents.FindControl("lbTxtBoxEnd" + i) as TextBox;

                        if (begintime != null && endtime != null)
                        {
                            if (!string.IsNullOrEmpty(begintime.Text.Trim()) && !string.IsNullOrEmpty(endtime.Text.Trim()))
                            {
                                if (begintime.Text != endtime.Text)
                                {
                                    Where += string.Format(" AND [" + fieldName + "] BETWEEN '{0}' AND '{1}'", begintime.Text, endtime.Text);
                                }
                                else
                                {
                                    Where += " AND datediff(day," + fieldName + ",'" + begintime.Text.Trim() + "')=0";
                                }

                                //setViewState("lbTxtBoxBegin" + i, begintime.Text.Trim());
                                //setViewState("lbTxtBoxEnd" + i, endtime.Text.Trim());

                                urlwhere += "&" + fieldName + "_begin=" + begintime.Text.Trim();
                                urlwhere += "&" + fieldName + "_end=" + endtime.Text.Trim();
                            }
                            else
                            {
                                urlwhere += "&" + fieldName + "_begin=";
                                urlwhere += "&" + fieldName + "_end=";
                            }
                        }
                    }
                    break;
            }
        }

        SQLWhere = Where;

        return urlwhere;
    }


    /// <summary>
    /// 获取Where值,sql语句
    /// </summary>
    /// <returns></returns>
    public string getWhere()
    {
        geturlWhere();        
        return SQLWhere;
    }


    /// <summary>
    /// 功能模块表单ID
    /// </summary>  
    public int ModelFormID
    {
        get
        {
            int _modelFormId = 0;
            if (this.ViewState["ModelFormID"] != null)
            {
                _modelFormId = Convert.ToInt32(ViewState["ModelFormID"].ToString());
            }
            return _modelFormId;
        }
        set { this.ViewState["ModelFormID"] = value; }
    }

    /// <summary>
    /// 栏目ID
    /// </summary>
    public int TypeID
    {
        get
        {
            int _TypeID = 0;
            if (this.ViewState["TypeID"] != null)
            {
                _TypeID = Convert.ToInt32(ViewState["TypeID"].ToString());
            }
            return _TypeID;
        }
        set { this.ViewState["TypeID"] = value; }
    }
    

    /// <summary>
    /// 获取所有TypeID
    /// </summary>
    /// <param name="TypeID"></param>
    /// <returns></returns>
    private string GetAllTypeID(string TypeID)
    {
        string strResult = "";
        if (TypeID == "") return strResult;

        Whir.BLL.InfoType bll = new Whir.BLL.InfoType();
        DataSet ds = bll.GetChild(TypeID);

        try
        {
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    strResult += "," + ds.Tables[0].Rows[i]["TypeID"].ToString();
                    strResult += GetAllTypeID(ds.Tables[0].Rows[i]["TypeID"].ToString());
                }
            }
        }
        catch { }

        return strResult;
    }
}
